package daos;

import entitys.Partida;
import entitys.Time;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import utils.JpaUtils;

/**
 *
 * @author Amauri
 */
public class PartidaDAO {
    
    public void Salvar( Partida partida ){
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("TrabalhoFinal");
        EntityManager em = emf.createEntityManager();
        
        em.getTransaction().begin();
        em.persist(partida);
        em.getTransaction().commit();
        
        em.close();
        emf.close();
    }
      
      
    public void update(Partida partida) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            manager.getTransaction().begin();
            manager.merge(partida);
            manager.getTransaction().commit();
        } catch (Exception e) {
            manager.getTransaction().rollback();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
            
    public void delete(Partida partida) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            manager.getTransaction().begin();
            partida = manager.merge(partida);
            manager.remove(partida);
            manager.getTransaction().commit();
        } catch (Exception e) {
            manager.getTransaction().rollback();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
    
    public Partida findById(Integer id) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            return manager.find(Partida.class, id);
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
    
    public List<Partida> listAll(Long codigoCampeonato) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            Query query = manager.createQuery("select c from Partida c where c.campeonato.ID = " + String.valueOf(codigoCampeonato), Time.class);
            return query.getResultList();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
}
